﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using XrmLibrary.MessageStrings;

namespace XrmLibrary.Extensions
{
    public static class EntityCollectionExtensions
    {
        /// <summary>
        /// Gets the first entity from the EntityCollection and returns its ID (GUID).
        /// </summary>
        /// <param name="entityCollection">The entity collection.</param>
        /// <returns>The first entity id (GUID).</returns>
        public static Guid GetFirstEntityId(this EntityCollection entityCollection)
        {
            ValidateEntityCollectionContainsSingleEntity(entityCollection);
            Guid entityId = entityCollection.Entities.First().Id;
            return entityId;
        }

        private static void ValidateEntityCollectionContainsSingleEntity(EntityCollection entityCollection)
        {
            if(entityCollection.Entities.Count == 0)
            {
                throw new ArgumentException(ErrorStrings.ZeroEntitiesFoundInEntityCollection);
            }
            if(entityCollection.Entities.Count > 1)
            {
                throw new ArgumentException(ErrorStrings.MultipleMatchingEntitiesFoundInEntityCollection);
            }
        }

        public static Boolean HasNoEntities(this EntityCollection entities)
        {
            return entities.IsNull() || entities.Entities.Count == 0;
        }

        public static Boolean IsNull(this EntityCollection entities)
        {
            return entities.Entities == null;
        }

        public static Boolean HasOneOrMoreEntities(this EntityCollection entities)
        {
            return !entities.IsNull() && entities.Entities.Count > 0;
        }

        public static Boolean HasMultipleEntities(this EntityCollection entities)
        {
            return !entities.IsNull() && entities.Entities.Count > 1;
        }

        public static Boolean HasOneEntity(this EntityCollection entities)
        {
            return !entities.IsNull() && entities.Entities.Count == 1;
        }
    }
}
